package com.yjt.sousou.detail.parts;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.yjt.sousou.Api;
import com.yjt.sousou.R;
import com.yjt.sousou.base.BaseActivity;
import com.yjt.sousou.base.BaseEntity;
import com.yjt.sousou.base.PagingBean;
import com.yjt.sousou.detail.entity.EventNum;
import com.yjt.sousou.detail.entity.KindEntity;
import com.yjt.sousou.detail.entity.PartsEntity;
import com.yjt.sousou.detail.entity.RoomEntity;
import com.yjt.sousou.detail.entity.SaveParts;
import com.yjt.sousou.http.DialogCallback;
import com.yjt.sousou.user.LoginTag;
import com.yjt.sousou.utils.HDPreference;
import com.yjt.sousou.utils.RecyclerViewItemDecoration;
import com.yjt.sousou.widget.pop.ItemFilter;
import com.yjt.sousou.widget.pop.XPopup;
import com.yjt.sousou.widget.pop.interfaces.SimpleCallback;
import com.yjt.sousou.widget.pop.view.OrderFilterPop;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author chs
 * date：2019-10-25 10:23
 * des：物料列表中选择物料
 */
public class SelectPartsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.recycleview)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_has_selected)
    TextView mTHasSelected;
    @BindView(R.id.tv_room)
    TextView mTRoom;
    @BindView(R.id.tv_kind)
    TextView mTvKind;
    @BindView(R.id.ll_filter)
    LinearLayout mLlFilter;
    @BindView(R.id.et_keyword)
    EditText mEtKeyword;
    private String orderId = "";
    private String keyword = "";
    private String roomId = "";
    private String typeId = "";
    private PagingBean BEAN = new PagingBean();
    private boolean isRefresh = true;
    private PartsListAdapter mAdapter;
    private int clickPosition;
    private List<SaveParts> mSaveParts = new ArrayList<>();
    private List<ItemFilter> rooms = new ArrayList<>();
    private List<ItemFilter> kinds = new ArrayList<>();
    OrderFilterPop mPopRoom;
    OrderFilterPop mPopKind;

    @Override
    protected Object setContentLayout() {
        return R.layout.activity_parts;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mUserId = HDPreference.getUserId(LoginTag.USER_ID.name());
        mTvTitle.setText("选择配件");
        orderId = getIntent().getStringExtra("orderId");
        getRoomList();
        getKindList();
        initData();
        initRefreshLayout();
        initRecyclerView();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setEnabled(false);
        mRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light
        );
        mRefreshLayout.setProgressViewOffset(true, 120, 300);
        mRefreshLayout.setRefreshing(true);
        mRefreshLayout.setOnRefreshListener(this);
    }

    private void initRecyclerView() {
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(new RecyclerViewItemDecoration(this));
        mAdapter = new PartsListAdapter(R.layout.item_parts, new ArrayList<PartsEntity.DataEntity>());
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
        mAdapter.setOnItemClickListener(this);
    }

    /**
     * 获取库房列表
     */
    private void getRoomList() {
        OkGo.<RoomEntity>get(Api.get().getRoomList())
                .tag(this)
                .execute(new DialogCallback<RoomEntity>(RoomEntity.class, this) {
                    @Override
                    public void onSuccess(Response<RoomEntity> response) {
                        RoomEntity roomEntity = response.body();
                        if (roomEntity != null && roomEntity.getData().size() != 0) {
                            rooms.add(new ItemFilter("全部",""));
                            for (RoomEntity.DataBean room : roomEntity.getData()) {
                                rooms.add(new ItemFilter(room.getKufang(), room.getId()));
                            }
                        }
                    }
                });
    }

    /**
     * 获取种类列表
     */
    private void getKindList() {
        OkGo.<KindEntity>get(Api.get().getKindList())
                .tag(this)
                .execute(new DialogCallback<KindEntity>(KindEntity.class, this) {
                    @Override
                    public void onSuccess(Response<KindEntity> response) {
                        KindEntity kindEntity = response.body();
                        if (kindEntity != null && kindEntity.getData().size() != 0) {
                            kinds.add(new ItemFilter("全部",""));
                            for (KindEntity.DataEntity kind : kindEntity.getData()) {
                                kinds.add(new ItemFilter(kind.getType(), kind.getId()));
                            }
                        }
                    }
                });
    }

    private void initData() {
        OkGo.<PartsEntity>post(Api.get().getPartsList()).tag(this)
                .params("id", orderId)
                .params("kufang", roomId)
                .params("page", String.valueOf(BEAN.getPageIndex()))
                .params("keyword", keyword)
                .params("type", typeId)
                .execute(new DialogCallback<PartsEntity>(PartsEntity.class, this) {
                    @Override
                    public void onSuccess(Response<PartsEntity> response) {
                        PartsEntity entity = response.body();
                        mRefreshLayout.setRefreshing(false);
                        if ("0".equals(entity.getReturncode())) {
                            if (entity.getData() != null) {
                                setData(entity.getData());
                            } else {
                                showToast("没有数据");
                            }
                        } else {
                            if (isRefresh && BEAN.getPageIndex() == 1) {
                                setData(new ArrayList());
                            }
                            showToast("没有数据");
                        }
                    }
                });
    }

    private void setData(List data) {
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < BEAN.getPageSize()) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
        setSelected();
    }

    private void setSelected() {
        mSelectNum = 0;
        for (PartsEntity.DataEntity datum : mAdapter.getData()) {
            SaveParts saveParts = new SaveParts(datum.getId(), datum.getHave_num());
            mSaveParts.add(saveParts);
            mSelectNum += datum.getHave_num();
        }
        mTHasSelected.setText(String.valueOf(mSelectNum));
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        BEAN.setPageIndex(1);
        initData();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        clickPosition = position;
        EventBus.getDefault().postSticky(adapter.getData().get(position));
        Intent intent = new Intent(this, AddPartsActivity.class);
        startActivity(intent);
    }

    @Override
    public void onLoadMoreRequested() {
        isRefresh = false;
        BEAN.addIndex();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetSelectNum(EventNum eventNum) {
        PartsEntity.DataEntity selectedData = mAdapter.getData().get(clickPosition);
        selectedData.setHave_num(eventNum.num);
        mAdapter.notifyDataSetChanged();
        setSaveList(selectedData.getId(), eventNum.num);
        mTHasSelected.setText(String.valueOf(mSelectNum));
    }

    int mSelectNum;

    private void setSaveList(String key, int value) {
        mSelectNum = 0;
        boolean isExist = false;
        for (int i = 0; i < mSaveParts.size(); i++) {
            SaveParts item = mSaveParts.get(i);
            if (item.getKey().equals(key)) {
                isExist = true;
                item.setValue(value);
            }
            mSelectNum += item.getValue();
        }
        if (!isExist) {
            SaveParts saveParts = new SaveParts(key, value);
            mSaveParts.add(saveParts);
            mSelectNum += value;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.btn_save, R.id.tv_room, R.id.btn_filter, R.id.tv_kind})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                saveParts();
                break;
            case R.id.tv_room:
                showRoomPop();
                break;
            case R.id.tv_kind:
                showKindPop();
                break;
            case R.id.btn_filter:
                keyword = mEtKeyword.getText().toString();
                BEAN.setPageIndex(1);
                isRefresh = true;
                initData();
                break;
            default:
        }
    }
    private void showRoomPop() {
        if (mPopRoom == null) {
            mPopRoom = (OrderFilterPop) new XPopup.Builder(this)
                    .atView(mLlFilter)
                    .autoOpenSoftInput(false)
                    .dismissOnTouchOutside(false)
                    .hasSubOptions(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void id(int position, String id) {
                            super.id(position, id);
                            roomId = id;
                            BEAN.setPageIndex(1);
                            isRefresh = true;
                            initData();
                            mTRoom.setText(rooms.get(position).getName());
                        }

                        @Override
                        public void onDismiss() {
                            setDismissState(mTRoom);
                        }
                    })
                    .asCustom(new OrderFilterPop(this, rooms));
        }
        showOrDismiss(mPopRoom, mPopKind);
        setTextColor(mTRoom);
    }

    private void showKindPop() {
        if (mPopKind == null) {
            mPopKind = (OrderFilterPop) new XPopup.Builder(this)
                    .atView(mLlFilter)
                    .autoOpenSoftInput(false)
                    .dismissOnTouchOutside(false)
                    .hasSubOptions(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void id(int position, String id) {
                            super.id(position, id);
                            typeId = id;
                            BEAN.setPageIndex(1);
                            isRefresh = true;
                            initData();
                            mTvKind.setText(kinds.get(position).getName());
                        }

                        @Override
                        public void onDismiss() {
                            setDismissState(mTvKind);
                        }
                    })
                    .asCustom(new OrderFilterPop(this, kinds));
        }
        showOrDismiss(mPopKind, mPopRoom);
        setTextColor(mTvKind);
    }

    public static void showOrDismiss(OrderFilterPop p0, OrderFilterPop p1) {
        if (p0 != null) {
            if (p0.isShow()) {
                p0.dismiss();
            } else {
                p0.show();
            }
        }
        if (p1 != null && p1.isShow()) {
            p1.dismiss();
        }
    }

    public void setTextColor(TextView tv) {
        tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.tab_color_blue));
        tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.filter_arrow_up, 0);
    }

    public void setDismissState(TextView tv) {
        tv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.black));
        tv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.filter_arrow_down, 0);
    }

    private void saveParts() {
        Gson gson = new Gson();
        String json = gson.toJson(mSaveParts);
        OkGo.<BaseEntity>post(Api.get().getSaveParts()).tag(this)
                .params("id", orderId)
                .params("opt_uid", mUserId)
                .params("peijian_json", json)
                .execute(new DialogCallback<BaseEntity>(BaseEntity.class, this) {
                    @Override
                    public void onSuccess(Response<BaseEntity> response) {
                        BaseEntity entity = response.body();
                        if (entity.getReturncode().equals("0")) {
                            showToast("提交成功");
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            showToast("提交失败:" + entity.getReturnmsg());
                        }
                    }
                });
    }

}
